<template>
    <div ref="editContainer" :style="'width: 100%;height:' + this.height + 'px;'"></div>
</template>
<script>
import * as monaco from 'monaco-editor/esm/vs/editor/editor.main.js';
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import { getCurrentInstance, onMounted, watch } from 'vue';
self.MonacoEnvironment = {
    getWorker() {
        return new JsonWorker();
    },
};
export default {
    name: "PaasCodeEditor",
    props: {
        modelValue: {
            default: ""
        },
        height: {
            default: 400
        },
        scrollEnd: {
            default: false
        },
        config: {}
    },
    setup(props, { emit }) {
        let monacoEditor;
        const { proxy } = getCurrentInstance();
        watch(
            () => props.modelValue, (value) => {
                if (value !== monacoEditor?.getValue()) {
                    monacoEditor.setValue(value);
                }
            },
        );
        onMounted(() => {
            monacoEditor = monaco.editor.create(proxy.$refs.editContainer, { value: props.modelValue, ...props.config });
            monacoEditor.onDidChangeModelContent(() => {
                const currenValue = monacoEditor?.getValue();
                emit('update:modelValue', currenValue);
                if (props.scrollEnd) {
                    // 获取最后一行的行号
                    var lastLineNumber = monacoEditor.getModel().getLineCount();
                    console.log(lastLineNumber);
                    // 将编辑器滚动到最后一行
                    monacoEditor.revealLine(lastLineNumber, monaco.editor.ScrollType.Immediate);
                }
            });
            // 在页面大小变化时调整编辑器大小
            window.addEventListener('resize', function () {
                monacoEditor.layout();
            });
        });

        return {};
    }
};
</script>
